package ua.model;

import java.util.HashSet;


import ua.common.XmlManager;
import ua.validator.Validator;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamOmitField;


@XStreamAlias("role")
public class RoleBean 
{
	@XStreamOmitField
	private String id;
		
	@XStreamAsAttribute
	private String rolename;
	
	@XStreamOmitField
	private HashSet<UserBean> users;

	public RoleBean() {
		this.id="";
		this.rolename = "";
		this.users = new HashSet<UserBean>();
	}
	
	public RoleBean(String name) {
		this.id="";
		this.rolename = name;
		this.users = new HashSet<UserBean>();
	}
	
	public String getId(){
		return id;
	} 
	
	public void setId(String roleid){
		id=roleid;
	}
	
	public String getRolename() {
		return rolename;
	}

	public void setRolename(String name) {
		this.rolename = name;
	}

	public void setUsers(HashSet<UserBean> users) {
		this.users = users;
	}

	public HashSet<UserBean> getUsers() 
	{
		if (users == null) {
			users = new HashSet<UserBean>(); 
		}
		return users;
	}

	public UserBean addUserBean(UserBean user) {
		getUsers().add(user);
		user.getRoles().add(this);
		user.addRoleStr(this);
		return user;
	}

	public void removeUserBean(UserBean user) {
		getUsers().remove(user);
		user.getRoles().remove(this);
		user.removeRoleStr(this);
	}
		
	public String save()
	{
	    TomcatUsersBean tomcatUsersBean	=(TomcatUsersBean) XmlManager.getInstance().getObjectXml();
	    String validation="";
	    
		if (id!=""){
			/*Update RoleBean*/
			validation= Validator.getInstance().validateEditRole(id);
			if( validation.equals(""))
		        tomcatUsersBean.getRoleByName(id).setRolename(rolename);
			else
				return validation;
		    /*Update Role of all users*/
		}else{
			/*Add RoleBean*/
			validation= Validator.getInstance().validateInsertRole(tomcatUsersBean,id);
			if( validation.equals(""))
			   tomcatUsersBean.addRole(this);
			else
				return validation;
		}
	    tomcatUsersBean.save();
	    return "Saved";
	}
	
	public String delete()
	{
		String validation = Validator.getInstance().validateDeleteRole(id);
		if( validation.equals(""))
		{
			/*Delete Role of all users*/
			TomcatUsersBean tomcatUsersBean	=(TomcatUsersBean) XmlManager.getInstance().getObjectXml();
			
			for(UserBean user:tomcatUsersBean.getUsers())
			{
			  for(RoleBean role: user.getRoles())
			  {
				  if (role.getRolename().equals(id))
				     user.removeRoleBean(role);	  
			  }
			}
			/*Delete Role*/
			tomcatUsersBean.removeRole(tomcatUsersBean.getRoleByName(id));
			tomcatUsersBean.save();
			return "Deleted";
		}
		return validation;
	}
}
